package com.shujia.kafka

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}

import java.util.Properties

object Demo4KafkaTF {
  def main(args: Array[String]): Unit = {
    /**
     * 1、建立链接
     */

    val properties = new Properties()
    //指定kafka集群列表
    properties.setProperty("bootstrap.servers", "master:9092,node1:9092,node2:9092")

    //设置key 和value的序列化类
    properties.setProperty("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
    properties.setProperty("value.serializer", "org.apache.kafka.common.serialization.StringSerializer")

    properties.setProperty("transactional.id", "123")

    //创建生产者
    val producer = new KafkaProducer[String, String](properties)

    //1、开启事务
    producer.initTransactions()
    producer.beginTransaction()

    //发送数据
    producer.send(new ProducerRecord[String, String]("tf", "java"))

    Thread.sleep(10000)

    producer.send(new ProducerRecord[String, String]("tf", "spark"))

    //2、提交事务
    producer.commitTransaction()
    producer.close()

    /**
     * 消费者
     * --isolation-level read_committed 度已提交数据
     * kafka-console-consumer.sh --bootstrap-server master:9092,node1:9092,node2:9092 --from-beginning --isolation-level read_committed --topic tf
     */

  }

}
